<template>
	<van-overlay :show="show" @click="onClickHide">
	 <view v-if="show" class="wrapper">
		 <canvas :style="{ width: canvasW + 'px', height: canvasH + 'px' }"  canvas-id="myCanvas" id="myCanvas"></canvas>
	  </view>
      <view v-if="canvasH && isShow" class="foot" :style="{top: canvasH + 50 + 'px' }">
      	<view v-if="!isOpen"  @click.stop="subscribe"  class="my-button">保存到相册</view>
		<button v-else  class="my-button" open-type="openImg" @click="openImg">
			保存到相册
		</button>
      </view>	  
	</van-overlay>
</template>

<script>
	export default { 
		props:['isOpen'],
		data () {
			return {
				show: false,
				canvasW: '',
				canvasH: '',
				SystemInfo: {},
				goodsImg: {},
				ctx: {},
				codeData: '',
				bgImg: '',
				type: 1,
				isShow: false,
				num: 1
			}
		},
		methods: {
			showCanvas (data, bgImg, type) {
				uni.showLoading({
					title: '海报生成中',
					mask: true
				})
				this.show = true;
				this.bgImg = bgImg;
				this.type = type;
				if(this.type === 2) {
					this.creatCanvas();
					return
				};
				this.$http.qrcode(data).then(async res => {
					await this.blobToUrl(res.data.data);
					this.creatCanvas();
				});
			},
			blobToUrl (data) {
				   var fs = uni.getFileSystemManager();  
				   var that = this;
				   that.codeData = wx.env.USER_DATA_PATH + '/erweima'+ that.num +'.png';
				   fs.writeFile({
				      filePath: that.codeData,
				      data: data,  
				      encoding: 'base64',  
				      success(res) { 
						  that.num +=1;
						  return true;
					  },
					   fail(err) {  
						   return false;
					   }  
					});
			},
			onClickHide () {
				this.show = false;
				this.isShow = false;
				this.ctx.clearRect(0, 0, this.canvasW, this.canvasH);
				this.ctx.draw();
			},
	    	getImageInfo(image) {
				return new Promise((req, rej) => {
					uni.getImageInfo({
						src: image,
						success: function(res) {
							req(res)
						},
						fail(err) {
							// return false;
						    console.error(err, 2);
						}  
					});
				})	
			},
			getSystemInfo(){
				return new Promise((req, rej) => {
					uni.getSystemInfo({
					    success: function (res) {
					        req(res)
					    }
					});	
				})
			},
			subscribe () {
				let that = this;
				uni.requestSubscribeMessage({
				  tmplIds: ['cYmhS0BvZLh1BqAu1xXL7Etc7Nho7nDdOjfSvTnPcbE'],
				  success (res) { 
					  console.log('订阅消息成功');
				  },
				  fail (res) {
					  console.log('订阅消息失败', res);
				  },
				  complete () {
					  that.saveImg();
				  }
				})
			},
			openImg () {
				this.$toast("请打开相册授权");
				uni.openSetting({
				  success(res) {
				    console.log('openSetting true', res);
				  }
				});
			},
			saveImg () {
				let that = this;
				uni.canvasToTempFilePath({
				   canvasId: 'myCanvas',
				   success: function(res) {
					   console.log(res.tempFilePath)
				    // 在H5平台下，tempFilePath 为 base64
					uni.authorize({
					    scope: 'scope.writePhotosAlbum',
					    success() {
					       uni.saveImageToPhotosAlbum({
					           filePath: res.tempFilePath,
					           success: function () {
					       		that.$toast("图片保存成功");
					           }
					       });
					    },
						complete: function(res) {
							that.onClickHide();
						},
						fail: function (res) {
							console.log(res);
							
						}
					})
				    },
					fail: function(res) {
						console.log(res);
					}
				}, this);
			},
	    	async creatCanvas () {
				this.ctx = uni.createCanvasContext('myCanvas', this);
				this.SystemInfo = await this.getSystemInfo();
				this.goodsImg = await this.getImageInfo(this.bgImg);
				let ratio = this.goodsImg.width / this.goodsImg.height;
				this.canvasW = this.SystemInfo.windowWidth * 0.8133; // 画布宽度
				this.canvasH = this.canvasW/ratio;   // 画布高度 = 主图高度+二维码高度 + 文字图片的间距（大概50）
				
				if(this.type === 1) {
				   var data = this.$getStorage("myShare_userInfo");
				   var avatarUrl  = await this.getImageInfo(data.avatar);
				   var codeImg =  await this.getImageInfo(this.codeData);
				}
			     setTimeout(()=>{
					 // 填充背景色，白色
					 this.ctx.setFillStyle('#fff'); // 默认白色
					 // ctx.fillRect(0, 0, this.canvasW, this.canvasH); // fillRect(x,y,宽度，高度)
					 this.ctx.drawImage(this.goodsImg.path, 0, 0, this.canvasW, this.canvasH); // drawImage(图片路径,x,y,绘制图像的宽度，绘制图像的高度)
				     if(this.type === 1) {
						let scale = this.canvasW/this.goodsImg.width;
						let codeX = this.canvasW * 0.7;
						let codeY = this.canvasH - 1120 * 0.17 * scale;
						let textX = this.canvasW*0.23;
						let textY = this.canvasH  - 1120 * 0.28 * scale;
						let avatarX = this.canvasW*0.071
						let avatarY = this.canvasH - this.canvasW*0.07 - 1120 * 0.27 * scale;
						 this.ctx.drawImage(codeImg.path, codeX, codeY, this.canvasW*0.19, this.canvasW*0.19);
						 this.ctx.setFontSize(15); // setFontSize() 设置字体字号
						 this.ctx.setFillStyle('#333'); // setFillStyle() 设置字体颜色
						 this.ctx.fillText(data.name, textX, textY); // （文字，x，y）				
						 this.ctx.arc(avatarX + this.canvasW*0.07, avatarY + this.canvasW*0.07, this.canvasW*0.07, 0, 360);
						 this.ctx.clip();
						 this.ctx.drawImage(avatarUrl.path, avatarX, avatarY,  this.canvasW*0.07 *2,  this.canvasW*0.07 *2); // drawImage(图片路径,x,y,绘制图像的宽度，绘制图像的高度)
						 this.ctx.restore();
					 }
					 this.ctx.draw();
					 uni.hideLoading();
					 // setTimeout(()=>{
						 this.isShow = true;
					 // },200);
				 },200);
			
				
			}
		}
	}
</script>

<style lang="scss" scoped>
	.wrapper {
		width: 100%;
		height: 100%;
		position: relative;
		canvas {
			// width: 81.33%;
			// height: 72.22%;
			position: absolute;
			top:4%;
			left: 50%;
			transform: translateX(-50%);
		}
	}
	.foot {
		background-color: transparent;
		top: 0;
		.my-button {
			font-size: 32rpx;
			width: 520rpx;
		}
	}
	
</style>
